package com.tomasio.projects.lua.controllers;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import com.tomasio.projects.lua.api.MainService;
import com.tomasio.projects.lua.core.exception.CoreException;
import com.tomasio.projects.lua.forms.ApplicationForm;
import com.tomasio.projects.lua.model.Application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author dctp
 */
@Controller
@RequestMapping("/applications")
public class ApplicationsController {

    private final MainService mainService;

    @Autowired
    public ApplicationsController(MainService mainService) {
        this.mainService = mainService;
    }

    @RequestMapping({"/", "/index", ""})
    public String index(Model model, WebRequest request) {
        model.addAttribute("pageTitle","Aplicações");
        model.addAttribute("pageDescription","Lista de Aplicações");
        
        List<Map<Object, Object>> dataList = new ArrayList<Map<Object, Object>>();

        List<Application> applications = mainService.searchApplications("");

        for (Application application : applications) {
            Map<Object, Object> item = new HashMap<Object, Object>();

            item.put("name", application.getName());
            item.put("description", application.getDescription());

            dataList.add(item);
        }

        model.addAttribute("total", dataList.size());
        model.addAttribute("dataList", dataList);

        return "applications";
    }

    @RequestMapping("/new")
    public String newApplication(Model model) {

        model.addAttribute("pageTitle","Aplicações");
        model.addAttribute("pageDescription","Editar nova Aplicação");
        
        ApplicationForm form = new ApplicationForm();
        model.addAttribute(form);
        return "applications/form";

    }

    @RequestMapping("/edit")
    public String editApplication(Model model, WebRequest request) {
        ApplicationForm form = new ApplicationForm();
        String uidParam = request.getParameter("uid");
        if (uidParam == null) {
            return "redirect:index";
        }
        

        Application application = mainService.findApplication(uidParam);
        form.setUid(application.getUid());
        form.setName(application.getName());
        form.setDescription(application.getDescription());
        model.addAttribute(form);
        return "applications/form";
    }

    @RequestMapping("/save")
    public String saveApplication(Model model, @Valid ApplicationForm form,
            BindingResult bindingResult, WebRequest request) {

        if (bindingResult.hasErrors()) {
            return "applications/form";
        }

        Application application = new Application();
        application.setUid(form.getUid());
        application.setName(form.getName());
        application.setDescription(form.getDescription());
        

        try {
            if (application.getUid() == null) {
                String uid = mainService.createApplication(application);
                application.setUid(uid);
                model.addAttribute("successMessage", "Aplicação adicionada com sucesso!");
            } else {
                mainService.updateApplication(application);
                model.addAttribute("successMessage", "Aplicação atualizada com sucesso!");
            }

        } catch (CoreException ex) {
            model.addAttribute("errorMessage", ex.getMessage());
            return "applications/form";
        }

       

        model.addAttribute("data", application);

        return "applications/detail";

    }

    @RequestMapping("/detail")
    public String detailApplication(Model model, WebRequest request) {
        Map<Object, Object> data = new HashMap<Object, Object>();
        String uidParam = request.getParameter("uid");
        if (uidParam == null) {
            return "redirect:index";
        }
        
        Application application = mainService.findApplication(uidParam);
       
        model.addAttribute("data", application);
        return "applications/detail";
    }

    @RequestMapping("/remove")
    public String removeApplication(Model model, WebRequest request,
            final RedirectAttributes redirectAttributes) {
        Map<Object, Object> data = new HashMap<Object, Object>();
        String uidParam = request.getParameter("id");
        if (uidParam == null) {
            return "redirect:index";
        }
       

        try {
            mainService.removeApplication(uidParam);
            redirectAttributes.addFlashAttribute("successMessage", "Usuário foi removido com sucesso!");

        } catch (CoreException ex) {
            redirectAttributes.addFlashAttribute("errorMessage", ex.getMessage());
            return "redirect:index";
        }

        return "redirect:index";
    }
}
